package controllers

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"social-app/models"
	"social-app/pkg/encryp"
	"social-app/pkg/err_msg"
	"social-app/pkg/jwt_token"
	"social-app/pkg/response"
	"social-app/pkg/utils"
	"time"
)

type UserController struct{}
type UserResponse struct {
	Token string `json:"token"`
}

func (u UserController) Login(c *gin.Context) {
	type reqParams struct {
		Username string `json:"username" binding:"required"`
		Password string `json:"password" binding:"required"`
	}
	var params reqParams
	if err := c.ShouldBind(&params); err != nil {
		panic(err_msg.TranslateParamsErr(err, nil))
	}

	user, _ := models.GetUserByUsername(params.Username)
	fmt.Println(user)
	if user.Id == 0 {
		panic("用户名或密码错误")
	}

	if encryp.Md5(params.Password) != user.Password {
		panic("账号或密码错误")
	}
	token, err := jwt_token.Encode(jwt_token.User{
		UserId:   user.Id,
		Username: user.Username,
		Time:     time.Now(),
	})
	if err != nil {
		panic(fmt.Sprintf("系统错误：凭证创建失败: %s", err.Error()))
	}

	data, err := models.WriteUserLoginLogger(user.Id, c.ClientIP())
	if err != nil {
		_ = data
		panic(err.Error())
	}
	response.Success(c, "登录成功", UserResponse{
		Token: token,
	})
}

func (u UserController) Register(c *gin.Context) {
	type reqParams struct {
		Username    string `json:"username" binding:"required"`
		Password    string `json:"password" binding:"required"`
		CmfPassword string `json:"cmf_password" binding:"required"`
		WxOpenid    string `json:"wx_openid"`
	}
	var params reqParams
	if err := c.ShouldBind(&params); err != nil {
		panic(err_msg.TranslateParamsErr(err, nil))
	}

	if params.Password != params.CmfPassword {
		panic("重复密码不一致")
	}
	user, _ := models.GetUserByUsername(params.Username)
	if user.Id != 0 {
		panic("用户名已被占用")
	}
	regIp := c.ClientIP()

	user = models.CreateUser(params.Username, encryp.Md5(params.Password), regIp, params.WxOpenid)
	if user.Id == 0 {
		panic("注册失败")
	}
	token, err := jwt_token.Encode(jwt_token.User{
		UserId:   user.Id,
		Username: user.Username,
		Time:     time.Now(),
	})
	if err != nil {
		panic(fmt.Sprintf("系统错误：凭证创建失败: %s", err.Error()))
	}
	response.Success(c, "注册用户成功", UserResponse{
		Token: token,
	})
}

func (u UserController) GetUserInfo(c *gin.Context) {
	userId := jwt_token.GetUserId(c)
	user, _ := models.GetUserById(userId)
	if user.Id == 0 {
		panic("用户不存在")
	}
	userInfo, _ := models.GetUserProfileByUserId(userId)
	if userInfo.Id == 0 {
		panic("用户信息错误")
	}
	type userProfileResponse struct {
		UserId   int    `json:"user_id"`
		Username string `json:"username"`
		Avatar   string `json:"avatar"`
		Intro    string `json:"intro"`
		Address  string `json:"address"`
		Sex      int    `json:"sex"`
		SexText  string `json:"sex_text"`
		Age      int    `json:"age"`
		Birthday string `json:"birthday"`
	}
	response.Success(c, "获取用户信息成功", userProfileResponse{
		UserId:   userId,
		Username: user.Username,
		Avatar:   utils.GetAvatar(userInfo.Avatar),
		Intro:    userInfo.Intro,
		Address:  userInfo.Address,
		Sex:      userInfo.Sex,
		SexText:  utils.GetSexText(userInfo.Sex),
		Age:      utils.BirthdayToAge(userInfo.Birthday),
		Birthday: userInfo.Birthday.Format("2006-01-02 15:04:05"),
	})
}

func (u UserController) SetUserProfile(c *gin.Context) {
	type reqParams struct {
		Avatar     string `json:"avatar"`
		Intro      string `json:"intro"`
		Sex        int    `json:"sex" binding:"oneof=0 1 2"`
		WechatCode string `json:"wechat_code"`
		Address    string `json:"address"`
		Birthday   string `json:"birthday" binding:"datetime=2006-01-02 15:04:05"`
	}

	var params reqParams
	if err := c.ShouldBind(&params); err != nil {
		panic(err_msg.TranslateParamsErr(err, nil))
	}

	userId := jwt_token.GetUserId(c)

	err := models.UpdateUserProfileByUserId(userId, params.Avatar, params.Intro, params.Sex, params.WechatCode, params.Address, params.Birthday)
	if err != nil {
		panic(err.Error())
	}
	response.Success(c, "保存用户信息成功", params)
}
